﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace PmuRegistry.Web
{
	public partial class Default : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
            PreRender += new EventHandler(Default_PreRender);
		}

        void Default_PreRender(object sender, EventArgs e)
        {
            RepeaterStatistics.DataSource = GetDeviceStatistics();
            RepeaterStatistics.DataBind();
        }

        DataTable GetDeviceStatistics()
        {
            SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["PmuRegistryConnection"].ConnectionString);
            DataTable resultTable = new DataTable();
            try
            {
                SqlCommand command = new SqlCommand("Select * From DeviceStatistics", connection);                
                command.Connection.Open();
                resultTable.Load(command.ExecuteReader());
                if (resultTable.Rows.Count > 0)
                {
                    LabelTotalDeviceCount.Text = resultTable.AsEnumerable().Sum(x => x.Field<int>("DeviceCount")).ToString();
                    LabelTotalMeasuredLines.Text = resultTable.AsEnumerable().Sum(x=>x.Field<int>("MeasuredLines")).ToString();
                }
                else
                {
                    LabelTotalDeviceCount.Text = "0";
                    LabelTotalMeasuredLines.Text = "0";
                }
            }            
            finally
            {
                connection.Close();
                connection.Dispose();
            }
            return resultTable;
        }
	}
}
